import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/modle/more/bloc/video_bloc.dart';
import 'package:shopping_group/modle/more/entity/group_simple4fuli_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/utils/log_util.dart';
import 'package:shopping_group/utils/video_player_util.dart';

class VideoFlPage extends StatefulWidget {
  final String groupSpecId;
  final String pushId;
  final String videoFileId;
  final String videoUrl;
  final GroupSimple4FuliEntity entity;
  VideoFlPage(
      {Key key,
      @required this.groupSpecId,
      @required this.pushId,
      @required this.videoUrl,
      @required this.videoFileId,
      @required this.entity})
      : super(key: key);

  @override
  _VideoFlPageState createState() => _VideoFlPageState();
}

class _VideoFlPageState extends State<VideoFlPage> with WidgetsBindingObserver {
  VideoPlayerUtil ijkPlayerUtil;
  StreamSubscription _videoSubscription;
  StreamSubscription _timeSubscription;
  VideoBloc _bloc;
  String _time = '0';
  Timer _countdownTimer;
  @override
  void initState() {
    super.initState();
    _bloc = VideoBloc();
    WidgetsBinding.instance.addObserver(this);
    ijkPlayerUtil = VideoPlayerUtil();
    // int url = Utils.getRandomInt(0, 2);
    LogUtil.e(this.widget.videoUrl,
        tag: 'Utils.getRandomInt url////////////////////');
    // String videoUrl = BaseConstant.videoUrlList[url];
    ijkPlayerUtil.initVideoPlayer(this.widget.videoUrl);

    // _videoSubscription = eventBus.on<VideoCompleteEvent>().listen((event) {
    //   if (!mounted) {
    //     return;
    //   }
    //   cancelTimer();
    //   ijkPlayerUtil.dispose();
    //   Map<String, dynamic> data = {};
    //   data['groupSpecId'] = this.widget.groupSpecId;
    //   data['pushId'] = this.widget.pushId;
    //   data['videoFileId'] = this.widget.videoFileId;
    //   data['userId'] = BaseConstant.userId;
    //   data['entity'] = this.widget.entity;
    //   _bloc.initFlDate.add(data);
    // });

    _videoSubscription = eventBus.on<VideoTimeEvent>().listen((event) {
      if (!mounted) {
        return;
      }
      setState(() {
        _time = event.time;
      });
    });

    _countdownTimer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (!mounted) {
        return;
      }
      setState(() {
        if ('0' != _time) {
          _time = (int.parse(_time) - 1).toString();
        }
        if ('1' == _time) {
          cancelTimer();
          ijkPlayerUtil.closeView();
          Map<String, dynamic> data = {};
          data['groupSpecId'] = this.widget.groupSpecId;
          data['pushId'] = this.widget.pushId;
          data['videoFileId'] = this.widget.videoFileId;
          data['userId'] = BaseConstant.userId;
          data['entity'] = this.widget.entity;
          _bloc.initFlDate.add(data);
        }
      });
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print("--" + state.toString());
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        break;
      case AppLifecycleState.resumed: // 应用程序可见，前台
        break;
      case AppLifecycleState.paused: // 应用程序不可见，后台
        break;
      case AppLifecycleState.detached: // 申请将暂时暂停
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: (() {
          FocusScope.of(context).requestFocus(FocusNode());
        }),
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          body: Container(
            height: MediaQuery.of(context).size.height,
            decoration: BoxDecoration(
              color: Colours.title_white,
            ),
            alignment: Alignment.center,
            child: ijkPlayerUtil.initView(context, time: _time),
          ),
        ));
  }

  void cancelTimer() {
    if (_countdownTimer != null) {
      _countdownTimer.cancel();
      _countdownTimer = null;
    }
  }

  @override
  void dispose() {
    cancelTimer();
    WidgetsBinding.instance.removeObserver(this);
    ijkPlayerUtil.dispose();
    BotToast.cleanAll();
    _videoSubscription?.cancel();
    _timeSubscription?.cancel();
    super.dispose();
  }
}
